package com.ms.base.web.error;

import com.ms.base.comm.cloud.BaseException;
import com.ms.base.comm.cloud.ResultDto;
import com.ms.base.comm.cloud.ResultException;
import com.ms.base.comm.cloud.ResultUtil;
import com.ms.base.comm.util.FrameUtil;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

/**
 * <b>description</b>： <br>
 * <b>time</b>：2018-07-31 16:19 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class GlobalErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Throwable error = getError(webRequest);
        ResultDto<Object> resultDto = null;
        if (error != null) {
            while (error instanceof Exception && error.getCause() != null) {
                error = error.getCause();
            }
            if (error instanceof ResultException) {
                ResultException e = (ResultException) error;
                resultDto = e.getResultDto();
            } else if (error instanceof BaseException) {
                BaseException e = (BaseException) error;
                resultDto = ResultUtil.resultDto(e);
            } else {
                resultDto = ResultUtil.error(error.getMessage());
            }
            //异常堆栈信息
            if (includeStackTrace) {
                resultDto.putExtData("trace", FrameUtil.stackTrace(error));
            }
        } else {
            resultDto = ResultUtil.errorSubCode("404", "您访问的资源不存在!");
        }
        try {
            return resultDto.map();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
